/**
 *	Plug in pour le jeu d'entrainement cerebral avec des cartes a jouer
 *	@author	Artiom FEDOROV
 */
 
 
(function($) {

	var imagesPath = "images/cards/";
	var apiPath = "json.php";
	
	var gameMode = "train";
	var userName = "Inconnu";
	
	
	var controllerPointer;
	var gamePointer;
	var mon1Pointer;
	var mon2Pointer;
	var mon3Pointer;
	var mon4Pointer;
	
	
	var cardsArr = [];
	
	var templateCards = "<div class='cards'></div>";
	
	var tempateCard = "<img src=\"" + "imagesPath" + "card" +"\" />";
	
	var somme = 0;
	
	var challengeLock = false;
	
	var running = false;
	var time = 0;		// current
	var timeStep = 100;		// centiemes de seconde car 1000 / 10 = cent
	$.fn.cardsCounter=function() {

		return this.each(function() {

			gamePointer = $(this).find(".game-main");
			mon1Pointer = $(this).find(".game-mon1");
			mon2Pointer = $(this).find(".game-mon2");
			mon3Pointer = $(this).find(".game-mon3");
			mon4Pointer = $(this).find(".game-mon4");
			
			
			controllerPointer = $(this).find(".game-controller");
			gamePointer.html(Mustache.render(templateCards));
			cardsPointer = gamePointer.find(".cards")
			
			controllerUsers = $(this).find(".game-controller-checkUserResult");
			controllerUserName = $(this).find(".game-controller-username");
			
			setMode();
			if (gameMode=='challenge') {
				createUserNamePromt();
			}
			
			
			loadCards();
			
			createControllers();
			createMonitors();
			
		});
		   
	};
		   

	function setMode() {
		 var anchorName = document.location.hash.substring(1);
		 gameMode = anchorName;
	}	
	
	
	function createControllers() {
	
		$(".game-controller-next")
			.html('<button type="button" class="btn btn-default NextCard" aria-label="Left Align">Next</button>');
			
		controllerPointer.find(".NextCard").click(function() {
			showNextCard();
		});
		cardsPointer.click(function() {
			showNextCard();
		});
		
		$(".game-controller-reload")
			.append('<button type="button" class="btn btn-default ReloadCards" aria-label="Left Align">Reload <span class="glyphicon glyphicon-refresh"></span></button>');
		controllerPointer.find(".ReloadCards").click(function() {
			somme = 0;
			challengeLock == false;
			running = false;
			time=0;
			controllerUsers.empty();
			loadCards();
		});
			
	}

	/**
	 *	Methode qui charge les cartes via api
	 *	c'est lapi qui est chargée du shuffle des cartes
	 *
	 */
	
	
	function loadCards() {
	
		 console.log("LOADDDIIINNNGGGG");
		cardsArr = [];
		 $.getJSON(apiPath, function(data) {
           
            cardsArr = data;
            showBackCard();
            
          });    
	}
	
	
	
	function gameStartsCallback() {
		
			 setTimeout(function(){ 
			 	updateMonitor2(); 
			 	time += timeStep;
			 	if (running == true) { 
			 		gameStartsCallback(); 
			 	} 
			 }, timeStep);
	}
	
	
	
	/**
	 *	Action principale! C'est celle qui lance le programme et qui enchaine les cartes
	 *
	 */
	
	function showNextCard() {
	
		if (gameMode == 'challenge') {
		//	createUserNamePromt
			//controllerUserName.
		}
	
	
	
		if (challengeLock == false) {
			var card = cardsArr.pop();
			// On detecte s'il s'agit d'un tout debut de partie et non de la pause en fin de lot
			if (running == false && (card !== undefined)) {
				time = 0;
				gameStartsCallback();
			}
	
			running = true;
		
			if (gameMode == 'train') {
		
			} else {
		
				var restCards = cardsArr.length;
			
				if (restCards == 1) {
					 checkUserResult();
				}
			
			}
		
		
			if (card === undefined) {
			 	
			 	running = false;
			 	showBackCard();
			 	
			} else {
		
				//console.log(card);
				//console.log(cardsArr);
				cardsPointer.html("<img src=\"" + imagesPath + card.file +"\" />");
				somme += card.score;
				console.log("somme : " + somme);
			}
		
			updateMonitors();
			
		}
	}
	
	
	/**
	 *	Methode qui se charge de verifier le score de l'utilisateur
	 *
	 */
	
	function checkUserResult() {

		updateMonitor2();
		
		// On arrete l'execution			
		running = false;
		challengeLock = true;
		// Template pour demander le score
		var str = '<form class="form-inline"> <div class="form-group">   <input size="3" type="text" class="form-control userResponse"><button type="button" class="btn btn-default sendScore">ok</button></div></form>';
		str = '<div class="panel panel-default"> <div class="panel-heading">Numéro de la derniere carte?</div><div class="panel-body">'+str+'</div></div>'
		// Injection du template
		controllerUsers.html(str);
	
		// Validation
		controllerUsers.find(".sendScore").click(function() {
			var response = controllerUsers.find(".userResponse").val();
			
			//alert("response:" + response);
			
			console.log("userResp" + parseInt(response));
			
			if (parseInt(response) == (180 - somme)) {
				console.log("Bonne REPONSE");
				sendScore();
				
				addDataMonitor4("Bonne reponse", "alert alert-success");
				
			} else {
				console.log("Mauvaise reponse REPONSE");
				addDataMonitor4("Mauvaise reponse", "alert alert-danger");
				
				
			}
			
			controllerUsers.empty();
			challengeLock = false;
			
			
		});			
			
	}
	
	
	function createUserNamePromt() {
	
	
		var str = '<form class="navbar-form navbar-right"> <div class="form-group">   <input type="text" placeholder="Pseudo" class="form-control userName"><button type="button" class="btn btn-default sendUserName">ok</button></div></form>';
		
		
		
		// Injection du template
		controllerUserName.html(str);
	
		// Validation
		
		controllerUserName.find(".sendUserName").click(function() {
		
			var attr = controllerUserName.find(".userName").attr('disabled');

			if ((typeof attr !== typeof undefined && attr !== false)) {
				
				$(this).text("Ok");
				controllerUserName.find(".userName").removeAttr("disabled");			

			} else {
				$(this).text("Edit");
				userName = controllerUserName.find(".userName").val();
				controllerUserName.find(".userName").attr("disabled", "disabled");
				
			}
		});			

	
	
	}	


	
	function sendScore() {
		
		var message = {};
		message.time = time - timeStep;	// Soustraction pour gestion d'un effet de bords
		message.pseudo = userName;
		$.get(apiPath + '?action=addScore', message, function(data) {
			console.log(data);
		});
	}
	
	
	
	function showBackCard() {

		cardsPointer.html("<img src=\"images/back.jpg\" />");
		updateMonitors();
	}
	
	
	
	function createMonitors() {

		if (gameMode=="train") {	
			createMonitor1();
		}
		
		createMonitor2();
		createMonitor3();
	}
	
	function updateMonitors() {
		
		if (gameMode=="train") {
			updateMonitor1();		// Somme courante
		}
		updateMonitor2();
		updateMonitor3();
	}
	
	function createMonitor1() {
		mon1Pointer.html("<div class=\"somme\">Somme : <span class=\"sommeSpan\">0</span></div>");
	}
	
	function createMonitor2() {
		mon2Pointer.html("<div class=\"digits timer\">Time : <span class=\"digits timerSpan\">0</span></div>");
	}
	
	
	function createMonitor3() {
		mon3Pointer.html("<div class=\"currentCard\"></div>");
	}
	
	
	
	function updateMonitor1() {
		mon1Pointer.find(".sommeSpan").text(somme);
	}
	
	
	function addDataMonitor4(text, classe) {
		if (classe=== undefined) {
			 classe = "alert alert-success";
		}
		var str='<div class="'+classe+'">' + text + '</div>'
		mon4Pointer.prepend(str);
	}

	/**
	 * Moniteur 2 est le timer
	 *
	 */

	function updateMonitor2() {
		if (time == 0) {
			mon2Pointer.find(".timerSpan").text("0");
		} else {
			mon2Pointer.find(".timerSpan").text(time / 1000 + " ");
		}
	}
	

	/**
	 * Moniteur 3 est l'indicateur de cartes restantes
	 *
	 */
	
	function updateMonitor3() {

		var count = cardsArr.length;
		var str = "";
		for(i = 0; i < count; i++) {
			//console.log(i);
			str = str + "<img width='10px' src=\"images/back.jpg\"/>";
		}
		
		mon3Pointer.find(".currentCard").html(str);
	}	
	
	   	
})(jQuery);
